package yxy.game.pm2.command.tower;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.currency.CurrencyNotEnoughException;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.TowerMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.tower.TowerHandle;
import yxy.game.pm2.module.tower.TowerModule;

/** 修炼塔 挑战次数购买 */
@MessageType(proto = Command.TowerChanllengePurchase, classtype = TowerMessage.TowerChanllengePurchaseRequest.class)
public class CMD_TowerChanllengePurchase extends Command<TowerMessage.TowerChanllengePurchaseRequest> {

	@Override
	public void execute(MessageSource messageSource, TowerMessage.TowerChanllengePurchaseRequest request) {
		String playerCode = messageSource.getTag();
		int times = request.getTimes();

		TowerMessage.TowerChanllengePurchaseResponse.Builder response = TowerMessage.TowerChanllengePurchaseResponse.newBuilder();

		TowerModule towerModule = TowerModule.get(playerCode);
		try {
			if (towerModule.tryLock()) {
				int cost = TowerHandle.buytimescost(towerModule.getBuytimes());

				if (times <= 0) {
					send(messageSource, response, Result.ParamError);
					return;
				}

				if (towerModule.remainBuyTimes() < times) {
					send(messageSource, response, Result.TowerBuyTimesLack);// 已经没有购买次数了
					return;
				}

				try {
					new CurrencyHandle().cost(playerCode, CCReason.修炼塔, Currency.create(CurrencyType.CT_元宝, 0, cost));
				} catch (CurrencyNotEnoughException e) {
					send(messageSource, response, new Result(Result.CostFail, e.getType().getNumber(), e.getDataId()));// 消费不足
					return;
				}
				towerModule.setBuytimes(towerModule.getBuytimes() + times);
				towerModule.setTimes(towerModule.getTimes() - times);
				towerModule.set();

				cost = TowerHandle.buytimescost(towerModule.getBuytimes());

				response.setTimes(towerModule.remainTimes());
				response.setBuytimes(towerModule.remainBuyTimes());
				response.setBuycost(cost);

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			towerModule.unlock();
		}
	}

	private void send(MessageSource messageSource, TowerMessage.TowerChanllengePurchaseResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}